# -*- coding: utf-8 -*-

'''eof
name:月均订烟单价（LT）
code:AvgPrice_LT
tableName:
columnName:
groups:烟商
dependencies:BTM
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime
import numpy as np

reload(sys)
sys.setdefaultencoding('utf-8')


def AvgPrice_LT():
    null_type_list = ['', None, 'null', 'Null', '/', ' ']
    money_month = {'T12':[], 'T11':[], 'T10':[], 'T9':[], 'T8':[], 'T7':[], 'T6':[], 'T5':[],
                       'T4':[], 'T3':[], 'T2':[], 'T1':[]}
    account_month = {'T12':[], 'T11':[], 'T10':[], 'T9':[], 'T8':[], 'T7':[], 'T6':[], 'T5':[],
                       'T4':[], 'T3':[], 'T2':[], 'T1':[]}

    avg_price = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_months_list = [
                (ApplTime - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                for i in xrange(12, -1, -1)]
        else:
            last_year_months_list = [
                (datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                for i in xrange(12, -1, -1)]
    except:
        return u'缺失值'

    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and len(BTM_['indent']) >= 1:
            for i in BTM_['indent']:
                if i.has_key('indentDate') and Formate(i['indentDate']) not in null_type_list \
                    and i.has_key('indentMoney') and i['indentMoney'] not in null_type_list \
                    and isfloat(i['indentMoney']) \
                    and i.has_key('indentAccount') and i['indentAccount'] not in null_type_list \
                    and isfloat(i['indentAccount']) \
                    and Formate(i['indentDate']) is not None \
                    and Formate(i['indentDate']) > last_year_months_list[0] and Formate(i['indentDate']) <= last_year_months_list[-1]:
                    if Formate(i['indentDate']) > last_year_months_list[0] and Formate(i['indentDate']) <= last_year_months_list[1]:
                        money_month['T12'].append(float(i['indentMoney']))
                        account_month['T12'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[1] and Formate(i['indentDate']) <= last_year_months_list[2]:
                        money_month['T11'].append(float(i['indentMoney']))
                        account_month['T11'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[2] and Formate(i['indentDate']) <= last_year_months_list[3]:
                        money_month['T10'].append(float(i['indentMoney']))
                        account_month['T10'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[3] and Formate(i['indentDate']) <= last_year_months_list[4]:
                        money_month['T9'].append(float(i['indentMoney']))
                        account_month['T9'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[4] and Formate(i['indentDate']) <= last_year_months_list[5]:
                        money_month['T8'].append(float(i['indentMoney']))
                        account_month['T8'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[5] and Formate(i['indentDate']) <= last_year_months_list[6]:
                        money_month['T7'].append(float(i['indentMoney']))
                        account_month['T7'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[6] and Formate(i['indentDate']) <= last_year_months_list[7]:
                        money_month['T6'].append(float(i['indentMoney']))
                        account_month['T6'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[7] and Formate(i['indentDate']) <= last_year_months_list[8]:
                        money_month['T5'].append(float(i['indentMoney']))
                        account_month['T5'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[8] and Formate(i['indentDate']) <= last_year_months_list[9]:
                        money_month['T4'].append(float(i['indentMoney']))
                        account_month['T4'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[9] and Formate(i['indentDate']) <= last_year_months_list[10]:
                        money_month['T3'].append(float(i['indentMoney']))
                        account_month['T3'].append(float(i['indentAccount']))
                    elif Formate(i['indentDate']) >  last_year_months_list[10] and Formate(i['indentDate']) <= last_year_months_list[11]:
                        money_month['T2'].append(float(i['indentMoney']))
                        account_month['T2'].append(float(i['indentAccount']))
                    else:
                        money_month['T1'].append(float(i['indentMoney']))
                        account_month['T1'].append(float(i['indentAccount']))
            for k in money_month.keys():
                if money_month[k] != [] and account_month[k] != [] and sum(account_month[k]) != float(0):
                    avg_price.append(float(sum(money_month[k]))/float(sum(account_month[k])))
            if avg_price != []:
                return round(float(np.mean(avg_price)), 4)
            else:
                return u'缺失值'
        else:
            return u'缺失值'
    except:
        return u'缺失值'

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False

#统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date
    # tmp = r.sub('',time)
    # try:
    #     if tmp.isdigit():
    #         date = datetime.datetime.strptime(tmp,'%Y%m%d').strftime('%Y%m%d')
    #         return date
    #     else:
    #         return None
    # except:
    #     return None

result = AvgPrice_LT()
